#include "mainwindow.h"
#include "ui_mainwindow.h"

PcmInputDevice::PcmInputDevice()
{
    m_inputFile.setFileName("../002_pcm_audio_play/002_pcm_audio_play.pcm");
    m_inputFile.open(QIODevice::ReadOnly);
}

void PcmInputDevice::start()
{
    open(QIODevice::ReadOnly);
}

void PcmInputDevice::stop()
{
    close();
}

PcmInputDevice::~PcmInputDevice()
{
    m_inputFile.close();
}

/**
 * \brief 扬声器缺少数据时会自动调用这个方法
 */
qint64 PcmInputDevice::readData(char *data, qint64 len)
{
    m_inputFile.read(data, len);

    return len;
}

qint64 PcmInputDevice::writeData(const char *data, qint64 len)
{
    Q_UNUSED(data);
    Q_UNUSED(len);

    return 0;
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_outputDevices = new QMediaDevices(this);
    m_outputDevice = m_outputDevices->defaultAudioOutput();
    QAudioFormat format = m_outputDevice.preferredFormat();
    // ChannelConfigStereo is 2, Int16 is 2
    qDebug("sampleRate: %d, channelCount: %d, sampleFormat: %d",
           format.sampleRate(), format.channelCount(), format.sampleFormat()
           );
    m_audioSinkOutput = new QAudioSink(m_outputDevice, format);

    m_pcmInputDevice = new PcmInputDevice;
    m_pcmInputDevice->start();
    m_audioSinkOutput->start(m_pcmInputDevice);
}

MainWindow::~MainWindow()
{
    m_pcmInputDevice->stop();
    m_audioSinkOutput->stop();
    delete ui;
}

